<template>
  <div class="favorites-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>我的收藏</h2>
        <p>查看和管理您收藏的简历</p>
      </div>
      <div class="header-actions">
        <el-button @click="loadFavorites" :icon="Refresh" circle />
      </div>
    </div>

    <!-- 收藏列表 -->
    <div class="favorites-content">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>

      <div v-else-if="favorites.length === 0" class="empty-state">
        <el-empty description="还没有收藏的简历">
          <el-button @click="$router.push('/resume-share')" type="primary">
            <el-icon><Plus /></el-icon>
            去发现简历
          </el-button>
        </el-empty>
      </div>

      <div v-else class="favorites-grid">
        <el-card
          v-for="favorite in paginatedFavorites"
          :key="favorite.id"
          class="favorite-card"
          shadow="hover"
        >
          <div class="card-header">
            <div class="card-title-section">
              <h3 class="card-title">{{ favorite.resume_name }}</h3>
              <el-tag :type="favorite.resume_type === 1 ? 'primary' : 'info'" size="small">
                {{ favorite.resume_type === 1 ? '创建的简历' : 'PDF简历' }}
              </el-tag>
            </div>
            <el-button
              text
              type="danger"
              size="small"
              @click="handleUnfavorite(favorite)"
              :icon="StarFilled"
            >
              取消收藏
            </el-button>
          </div>

          <div class="card-content">
            <div v-if="favorite.resume_type === 1" class="resume-info">
              <p v-if="favorite.template_id" class="info-item">
                <el-icon><Document /></el-icon>
                <span>模板ID: {{ favorite.template_id }}</span>
              </p>
              <p class="info-item">
                <el-icon><Calendar /></el-icon>
                <span>收藏时间: {{ formatDate(favorite.created_at) }}</span>
              </p>
            </div>

            <div v-else class="pdf-info">
              <p v-if="favorite.pdf_url" class="info-item">
                <el-icon><Document /></el-icon>
                <span>PDF文件</span>
              </p>
              <p class="info-item">
                <el-icon><Calendar /></el-icon>
                <span>收藏时间: {{ formatDate(favorite.created_at) }}</span>
              </p>
            </div>
          </div>

          <div class="card-actions">
            <el-button
              v-if="favorite.resume_type === 1"
              type="primary"
              size="small"
              @click="handleView(favorite.resume_id)"
            >
              <el-icon><View /></el-icon>
              查看简历
            </el-button>
            <el-button
              v-else
              type="primary"
              size="small"
              @click="handleViewPdf(favorite.pdf_url)"
            >
              <el-icon><View /></el-icon>
              查看PDF
            </el-button>
            <el-button
              v-if="favorite.resume_type === 1"
              type="success"
              size="small"
              @click="handleUseTemplate(favorite)"
            >
              <el-icon><Download /></el-icon>
              使用模板
            </el-button>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-container" v-if="favorites.length > 0">
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="totalFavorites"
        layout="prev, pager, next, total"
        :hide-on-single-page="true"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  StarFilled,
  View,
  Download,
  Calendar,
  Document,
  Refresh,
  Plus
} from '@element-plus/icons-vue';
import instance from '@/utils/request';

const router = useRouter();

// 数据
const favorites = ref([]);
const loading = ref(false);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(12); // 每页显示12条（3列，每列4条）
const totalFavorites = computed(() => favorites.value.length);

// 计算当前页显示的数据
const paginatedFavorites = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return favorites.value.slice(start, end);
});

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-';
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 加载收藏列表
const loadFavorites = async () => {
  loading.value = true;
  try {
    const response = await instance.get('/favorites', {
      params: {
        page: 1,
        pageSize: 1000 // 获取所有收藏，前端分页
      }
    });

    // 注意：response 已经是经过拦截器处理的 data，不是原始的 axios response
    if (response.code === 0) {
      favorites.value = response.data.list || [];
      currentPage.value = 1;
    } else {
      ElMessage.error(response.msg || '加载收藏列表失败');
    }
  } catch (error) {
    console.error('加载收藏列表失败:', error);
    ElMessage.error('加载收藏列表失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 取消收藏
const handleUnfavorite = async (favorite) => {
  try {
    await ElMessageBox.confirm('确定要取消收藏这份简历吗？', '确认取消收藏', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const response = await instance.delete(`/favorites/${favorite.id}`);

    // 注意：response 已经是经过拦截器处理的 data
    if (response.code === 0) {
      ElMessage.success('已取消收藏');
      loadFavorites(); // 重新加载列表
    } else {
      ElMessage.error(response.msg || '取消收藏失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消收藏失败:', error);
      ElMessage.error('取消收藏失败，请重试');
    }
  }
};

// 查看简历
const handleView = (resumeId) => {
  router.push(`/resume/${resumeId}`);
};

// 查看PDF
const handleViewPdf = (pdfUrl) => {
  if (pdfUrl) {
    window.open(pdfUrl, '_blank');
  } else {
    ElMessage.warning('PDF地址不存在');
  }
};

// 使用模板
const handleUseTemplate = (favorite) => {
  if (favorite.resume_type === 1 && favorite.resume_id) {
    router.push({
      path: '/editor',
      query: {
        id: favorite.resume_id,
        mode: 'template'
      }
    });
  } else {
    ElMessage.info('只有创建的简历才能使用模板功能');
  }
};

// 分页变化
const handlePageChange = (page) => {
  currentPage.value = page;
  window.scrollTo({ top: 0, behavior: 'smooth' });
};

// 初始化
onMounted(() => {
  loadFavorites();
});
</script>

<style scoped>
.favorites-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.15);
}

.header-left h2 {
  margin: 0 0 8px 0;
  color: #fff;
  font-size: 24px;
  font-weight: 600;
}

.header-left p {
  margin: 0;
  color: rgba(255, 255, 255, 0.8);
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.favorites-content {
  max-width: 1200px;
  margin: 0 auto;
}

.loading-container {
  padding: 40px;
  background: white;
  border-radius: 12px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 12px;
}

.favorites-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.favorite-card {
  border-radius: 12px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.favorite-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.card-title-section {
  flex: 1;
}

.card-title {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.card-content {
  margin-bottom: 16px;
  min-height: 60px;
}

.resume-info,
.pdf-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item {
  margin: 0;
  font-size: 13px;
  color: #666;
  display: flex;
  align-items: center;
  gap: 6px;
}

.card-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  padding: 20px;
  background: white;
  border-radius: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .favorites-grid {
    grid-template-columns: 1fr;
  }

  .page-header {
    flex-direction: column;
    gap: 20px;
  }

  .card-actions {
    flex-direction: column;
  }

  .card-actions .el-button {
    width: 100%;
  }
}
</style>

